<?php
/**
 * Created by PhpStorm.
 * User: kevin
 * Date: 15-6-16
 * Time: 上午10:30
 */
namespace Home\Controller;
use Think\Controller;
use User\Api\UserApi;
use Api\Department\DepartmentApi;
use Staff\Api\StaffApi;
class PublicController extends Controller {

    //用户注册页面 改为ajax方式提示
    public function register(){
        if(IS_POST) {
            $config = S('DB_CONFIG_DATA');
            if($config['USER_ALLOW_REGISTER'] == 0)
            {
                $this->error('管理员不允许注册，请联系管理员');
            }
            $arr            = I('post.');
            $username       = $arr['username'];
            $password       = $arr['password'];
            $repassword     = $arr['repassword'];
            $email          = $arr['email'];
            $tel            = $arr['tel'];
            $model = D('User');
            $uid = $model->register($username, $password, $email,$tel,$repassword);
            if($uid>0)
            {
                if ($this->userAddGuest($uid))
                {
                    $this->success('注册成功');
                }
                else
                {
                    $this->error('添加进普通用户组失败');
                }
            }
            else
            {
                $this->error($this->showRegError($uid));
            }
        }
    }
    //用户登录页面
    public function login(){
        if(IS_POST){
            $arr        = I('login');
            $username   = addslashes(trim($arr['username']));
            $password   = addslashes(trim($arr['password']));
            //保存用户登录信息  存入session
            $User   = D('User');
            $uid    = $User->login($username,$password);
            if($uid>0){
                D('User')->a_login($uid);  //自动登录
//                action_log('user_login','user',$uid,$uid);
                $result['result']=1;
                $this->ajaxReturn($result);
            }else{
                switch($uid){
                    case -1:$error='用户名不存在！';break;
                    case -2:$error='密码输入错误！';break;
                    case -3:$error='用户被禁用了! ';break;
                    case -4:$error='用户组不允许登录！! ';break;
                    default:$error='未知错误！';break;
                }
                $result['result']   =0;
                $result['msg']      =$error;
                $this->ajaxReturn($result);
            }
        }else{
            $value2 = cookie('remember_password');

            $value3 = cookie('remember_account');

            if($value2&&$value3)
            {
                $this->assign('pass',$value2);

                $this->assign('account',$value3);
            }

            $username=isset($_COOKIE["username"])?$_COOKIE["username"]:"";
            $password=isset($_COOKIE["password"])?$_COOKIE["password"]:"";
            $this->assign('username',$username);
            $this->assign('password',$password);

            $this->display();
        }
    }
	
	//统一身份登录
	public function idlogin(){
		$uid = $_GET['uid'];
		// D('User')->a_login($uid);
		
		if (D('User')->a_login($uid)) {
			$this->success('登录成功',U('Task/index'));
		} else {
			$this->error('登录失败');
		}
	}

    //验证码
    public function verify(){
        $verify = new \Think\Verify();
        $verify->entry(1);
    }

    /*
     * 用户退出
     */
    public function logout(){
        if(is_login()){
            $id = session('user_auth.uid');
            action_log('user_logout','user',$id,$id);
            D('User')->logout();
//            session(['destory']);
            $this->redirect('login');
        }else{
            $this->redirect('login');
        }
    }

    /*
     * 检测用户是否已经注册
     */
    public function checkUsername($username){
        $User = new UserApi();
        $check = $User->checkUsername($username);
    }

    /*
     * 用户找回密码
     */
    public function getPassword(){
        if(IS_POST){
            $user = new UserApi();
            $where['email'] = I('post.email');
            $info = $user->info(UID);
            if(!$info){
                $this->error('对不起找不到该用户信息');
            }
            $result = $this->_sendPasswordEmail($info);
//            print_r($result);die;
            $url = MODULE_NAME.'/'.CONTROLLER_NAME.'/resetPassword/code/'.$result;
            $content = '请登录如下地址去修改您的密码,http://plat.dev.com/'.$url;
            $res = think_send_mail($info['email'],$info['username'],"找回密码",$content);
            if($res){
                $this->success('请去您的注册邮箱查看邮件，按照指定操作来修改密码',U('Public/login'));
            }else{
                $this->error('对不起，无法找回密码，请联系客服人员');
            }
        }else{
            $this->display();
        }
    }

    /**
     * 重置密码页面
     * @return void
     */
    public function resetPassword() {
        if(IS_POST){
            $code = $_POST['code'];
            $user_info = $this->_checkResetPasswordCode($code);

            $password = trim($_POST['password']);
            $repassword = trim($_POST['repassword']);
            if($password != $repassword){
                $this->error('重复密码不一样');
            }

            $map['id'] = $user_info['id'];
            $data['password']   = md5($password);
            $res = D('User')->where($map)->save($data);
            if ($res) {
                D('find_password')->where('uid='.$user_info['id'])->setField('is_used',1);
                $this->success('修改成功',U('login'));
            } else {
                $this->error('失败');
            }
        }else{
            $code = ($_GET['code']);
            $this->_checkResetPasswordCode($code);
            $this->assign('code', $code);
            $this->display();
        }
    }

    /**
     * 检查重置密码的验证码操作
     * @return void
     */
    private function _checkResetPasswordCode($code) {
        $map['code'] = $code;
        $map['is_used'] = 0;
        $uid = D('find_password')->where($map)->getField('uid');
        if(!$uid){
            $this->assign('jumpUrl',U('Public/getPassword'));
            $this->error('重置密码链接已失效，请重新找回');
        }
        $user_info = M('User')->where("`id`={$uid}")->find();

        if (!$user_info) {
            $this->redirect = U('Public/login');
        }

        return $user_info;
    }

    private  function  _sendPasswordEmail($user){
        if($user['id']){
            $code = md5($user["id"].'+'.$user["password"].'+'.rand(1111,9999));
            $config['reseturl'] = U('Public/Public/resetPassword', array('code'=>$code));
            D('FindPassword')->where('uid='.$user["id"])->setField('is_used',1);
            $add['uid'] = $user['id'];
            $add['email'] = $user['email'];
            $add['code'] = $code;
            $add['is_used'] = 0;
            $result = D('FindPassword')->add($add);
            if($result){
                action_log(UID,"通过EMAIL找回密码");
                return $code;
            }else{
                return false;
            }
        }
    }

    /**
     * 获取用户注册错误信息
     * @param  integer $code 错误编码
     * @return string        错误信息
     */
    private function showRegError($code = 0){
        switch ($code) {
            case -1:  $error = '用户名长度必须在16个字符以内！'; break;
            case -2:  $error = '用户名被禁止注册！'; break;
            case -3:  $error = '用户名被占用！'; break;
            case -4:  $error = '密码长度必须在6-30个字符之间！'; break;
            case -5:  $error = '邮箱格式不正确！'; break;
            case -6:  $error = '邮箱长度必须在1-32个字符之间！'; break;
            case -7:  $error = '邮箱被禁止注册！'; break;
            case -8:  $error = '邮箱被占用！'; break;
            case -9:  $error = '手机号码格式不正确！'; break;
            case -10: $error = '对不起，你不符合注册条件！'; break;
            case -11: $error = '对不起,输入的密码和重复密码不一样！'; break;
            default:  $error = '未知错误';
        }
        return $error;
    }

    //注册用户添加到普通用户组
    private function userAddGuest($uid){
        $map['description'] = array('LIKE', '%普通用户%');
        $gid = M('AuthGroup')->where($map)->getField('id');
        $data = array(
            'uid'=>$uid,
            'group_id'=>$gid
        );
        if(M('AuthGroupAccess')->where($data)->find())
        {
            return -1;
        }
        else
        {
            $res = M('AuthGroupAccess')->add($data);
        }
        return $res;
    }
}